/**
 * author  bianlongting
 * date    2016-03-16
 * time    17:33
 * description  设置商品
 */

$(function(){
	var category = $(".shop-category .level-one");
	var warehouse = $(".shop-category .level-warehouse");
	var levelOne = $(".level-one");
	var levelTwo = $(".level-two");
	var search = $(".btn-search");	//搜索
	var setshop = $(".btn-setshop");	//设置商品
	var selectShop = $(".select-content");
	var deleteshop = $(".btn-deleteshop");	//删除商品
	var deletefullshop = $(".btn-deletefullshop");	//删除商品
	var shopContent = $(".shop-content");
	var page = $("#page");		//填充页码
	var data = {};		//缓存对象
	var pageIndex = 1;	//页码默认为第一页
	var pageCount;		//总页码
	var checkAll ,selectCheckbox ;

	//回车事件
	$(document).keypress(function(e) {  
       if(e.keyCode == 13) {  
  			search.trigger("click");
       }  
   }); 


	/*
	 * 获取URL参数
	 */
	function getParam(name){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
		var r = window.location.search.substr(1).match(reg); 
		if (r != null) return unescape(r[2]); return null; 
	}
	var flage = getParam("actId");
		flage = flage ? "1" : "0";
	//获取二级商品分类
	category.on("change",function(){
		var val = $(this).val();
		if (val != "") {
			$.ajax({
				url : "/index.php?m=Home&c=Activity%2FCreateCoupon&a=getcatTwoAction&catId=" + val,
				type : 'GET',
				dateType : 'JSON',
				success : function(data){
					if (data.success == true) {
						var data = data.data;
						if (data.length > 0) {
							renderDom(data);		//拼装商品二级分类
						}else{
							levelTwo.hide().html("");	//如果没有二级分类则不显示
						}
					}else{
						alert(data.message);
					}
				}
			})
		}else{
			levelTwo.hide().html("");
		}
	});

	function renderDom(data){
		levelTwo.html("");
		var html = "<select>";
		for (var i = 0; i < data.length; i++) {
			html += "<option value='" + data[i].id + "'> " + data[i].name +  " </option>";
		};
		html += "</select>";
		levelTwo.show().html(html);
	};

	//筛选商品
	search.on("click",function(){
		if (data.hasOwnProperty("page")) {
			delete data.page;
		};
		data.name = $(".shopName").val();
		data.sn = $(".shopSn").val();
		data.minprice = $(".minprice").val();
		data.maxprice = $(".maxprice").val();
		data.where = getParam('where');
		data.flage = flage;
		data.warehouseId = warehouse.val(); 
		if (levelTwo.hasClass('hide')) {
			data.catId = levelTwo.val();
		}else{
			data.catId = levelOne.val();
		};
		$.ajax({
			url : "/index.php?m=Home&c=Activity%2FCreateCoupon&a=getallgoodsAction",
			data : data,
			type : 'POST',
			dateType : 'JSON',
			success : function(data){
				if (data.success == true) {
					var data = data.data;
					if (data == "" || data == undefined) {
						shopContent.html("");
						page.html("");
				        toast("没有该类型的商品");
					}else{
						renderShopDom(data);		//拼装商品
					}
				}else{
					alert(data.message);
				}
			}
		})
	});

	//拼装筛选商品
	function renderShopDom(data){
		shopContent.html("");
		var html = "";
		$("#checkAll,#checkShopAll").html("<input type='checkbox'>");
		var shopArray = [];
		selectShop.find('input').each(function(index, el) {
			shopArray.push($(this).data().id);
		});
		for (var i = 0; i < data.goods.length; i++) {
			for (var j = 0; j < shopArray.length; j++) {
				if (data.goods[i].id == shopArray[j]) {
					delete data.goods[i].id;
				};
			};
			if (data.goods[i].id != undefined) {
				html += "<tr align='center'>\
						<td data-title='Code'>\
							<input type='checkbox' class='selectCheckbox' data-id=" + data.goods[i].id +">\
						</td>\
						<td>" + data.goods[i].id + "</td>\
						<td>" + data.goods[i].name + "</td>\
						<td class='numeric'>" + data.goods[i].sn + "</td>\
						<td class='numeric'>" + data.goods[i].price + "</td>\
						<td class='numeric'>" + data.goods[i].stock +"</td>\
					</tr>"
			};

		};
		shopContent.html(html);
		//全选框的选定和取消
		selectCheckbox = $(".selectCheckbox");
		checkAll = $("#checkAll input");
		checkAll.on("click",function(){
	        selectCheckbox.prop('checked', this.checked);
	    });
		selectCheckbox.on("click",function(){
	        var _tmp = selectCheckbox;
	        checkAll.prop('checked',_tmp.length == _tmp.filter(":checked").length);
	    });
		page.html(data.page);
		pageCount = Math.ceil(parseInt(data.count)/10);
		var oLis = page.find('ul li');
		oLis.eq(pageIndex -1 ).addClass('active')
						  .siblings().removeClass('active');
		changePage(pageCount);		//切换页码
	};

	//页码切换
	function changePage(num){
		page.find('a').on("click",function(e){
			e.preventDefault();
			var that = $(this);
			var parent = that.parent();
			if (parent.hasClass("next")) {
				if (pageIndex == num) {
					return false;
				}else{
					pageIndex ++ ;
				}
			}else if (parent.hasClass("prev")) {
				if (pageIndex == 1) {
					return false;
				}else{
					pageIndex -- ;
				}
			}else {
				pageIndex = parseInt(that.text());
			};
			data.p = pageIndex;

			$.ajax({
				url : "/index.php?m=Home&c=Activity%2FCreateCoupon&a=getallgoodsAction",
				data : data,
				type : 'GET',
				dateType : 'JSON',
				success : function(data){
					if (data.success == true) {
						var data = data.data;
						renderShopDom(data);		//拼装商品
					}else{
						alert(data.message);
					}
				}
			})
		})
	}

	//获取选择的商品
	var shopArr = [];
	setshop.on("click",function(){
		shopArr.length = 0;
		selectCheckbox.each(function(){
			if ($(this).prop("checked")) {
				shopArr.push($(this).parents("tr"));
			};
		})
		if (shopArr.length > 0) {
			for (var i = 0; i < shopArr.length; i++) {
				selectShop.append(shopArr[i]);
			};
			selectShop.find("input").each(function(){
				$(this).prop("checked",false);
			})
		}else{
			toast("至少选择一个商品");
		}
	})

	deleteshop.on("click",function(){
		selectShop.find("input").each(function(){
			if ($(this).prop("checked")) {
				$(this).parents("tr").remove();
			};
		})
	});

	//优惠券设置完成
	$(".btn-complete").on("click",function(){
		checkedShop();
	});

	//满减优惠券设置完成
	$(".btn-fullcart-complete").on("click",function(){
		checkedShop();
	});

	//提交选中的商品
	function checkedShop(){
		var completeArr = [];
		selectShop.find("input").each(function(index, el) {
			completeArr.push($(this).data().id);
		});
		$(".selectdShop").val(completeArr.toString());
		$("#shopForm").submit();
	}

	function toast(tip){
		$(".toast_tip").html(tip);
        $(".toast").fadeIn('1000');
        setTimeout(function(){
            $(".toast").fadeOut();
        },1000);
        return false;
	}
})


